package com.hgxd.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hgxd.entity.pojo.Organization;

import com.hgxd.mapper.EquipmentMapper;
import com.hgxd.mapper.OrganizationMapper;
import com.hgxd.service.IOrganizationService;
//import com.hgxd.utils.FsdUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 组织、项目表 服务实现类
 * </p>
 *
 * @author fsd
 * @since 2023-10-18
 */
@Service("OrganizationServiceImpl")
public class OrganizationServiceImpl extends ServiceImpl<OrganizationMapper, Organization> implements IOrganizationService {
    @Resource
    OrganizationMapper organizationMapper;

    @Resource
    private EquipmentMapper equipmentMapper;

    @Override
    public Integer getCountToSwitchroom() {
        return organizationMapper.getCountToSwitchroom();
    }

    @Override
    public List<Organization> getOrganizationForTree() {
        // 查询所有所有组织，根据level=3查询对应设备
        List<Organization> organizations = organizationMapper.selectList(null);
        List<Organization> parentOrganization = organizations.stream()
                .filter(organization -> organization.getParentId() == 0).collect(Collectors.toList());
        return setTreeForOrganization(organizations, parentOrganization);
    }

    @Override
    public List<Organization> getOrganizationAndLevel3() {
        return organizationMapper.getOrganizationAndLevel3();
    }


    /**
     * 为组织搭建树形结构
     * @param organizations
     * @param parentOrganizations
     * @return
     */
    private List<Organization> setTreeForOrganization(List<Organization> organizations, List<Organization> parentOrganizations) {
        // 遍历父组织
        for (Organization organization : parentOrganizations) {
            // 找子组织
            List<Organization> sonOrganizations = organizations.stream()
                    .filter(o -> organization.getId() == o.getParentId().longValue())
                    .collect(Collectors.toList());
            // 有子组织
            if (!sonOrganizations.isEmpty()) {
                List<Organization> organizationsNew = setTreeForOrganization(organizations, sonOrganizations);
                organization.setChildren(organizationsNew);
            }
        }
        return parentOrganizations;
    }
}
